import request from '@/utils/request'
import type { 
  CreateConfigGroup,
  UpdateConfigGroup,
  ConfigGroup
} from '@/types/api/config/configGroup'
import type {
  Config,
  CreateConfig,
  UpdateConfig,
  ConfigQuery,
} from '@/types/api/config/config'
import type { API } from '@/types/api/response'

/**
 * 获取配置分组列表
 */
export const getConfigGroups = async () => {
  try {
    return await request.get<API.Response<ConfigGroup[]>>('/api/config/setting/groups')
  } catch (error) {
    throw error
  }
}

/**
 * 获取配置分组详情
 * @param id 配置分组ID
 */
export const getConfigGroupDetail = (id: string) =>
  request.get<API.Response<ConfigGroup>>(`/api/config/group/${id}`)

/**
 * 创建配置分组
 * @param data 配置分组表单数据
 */
export const createConfigGroup = (data: CreateConfigGroup) =>
  request.post<API.Response<ConfigGroup>>('/api/config/group', data)

/**
 * 更新配置分组
 * @param id 配置分组ID
 * @param data 配置分组表单数据
 */
export const updateConfigGroup = (id: string, data: UpdateConfigGroup) =>
  request.put<API.Response<null>>(`/api/config/group/${id}`, data)

/**
 * 删除配置分组
 * @param id 配置分组ID
 */
export const deleteConfigGroup = (id: string) =>
  request.delete<API.Response<null>>(`/api/config/group/${id}`)

/**
 * 获取配置列表
 * @param params 查询参数
 */
export const getConfigList = (params: ConfigQuery) =>
  request.get<API.Response<Config[] | { list: Config[], total: number }>>('/api/config/list', { params })

/**
 * 获取配置分页列表
 * @param params 查询参数
 */
export const getConfigPage = (params: ConfigQuery) =>
  request.get<API.Response<API.PageResult<Config>>>('/api/config/page', { params })

/**
 * 获取配置详情
 * @param id 配置ID
 */
export const getConfigDetail = (id: string) =>
  request.get<API.Response<Config>>(`/api/config/${id}`)

/**
 * 创建配置
 * @param data 配置信息
 */
export const createConfig = (data: CreateConfig) =>
  request.post<API.Response<Config>>('/api/config', data)

/**
 * 更新配置
 * @param id 配置ID
 * @param data 配置信息
 */
export const updateConfig = (id: string, data: UpdateConfig) =>
  request.put<API.Response<null>>(`/api/config/${id}`, data)

/**
 * 删除配置
 * @param id 配置ID
 */
export const deleteConfig = (id: string) =>
  request.delete<API.Response<null>>(`/api/config/${id}`)

/**
 * 批量删除配置
 * @param ids 配置ID数组
 */
export const batchDeleteConfig = (ids: string[]) =>
  request.delete<API.Response<null>>('/api/config/batch', { data: { ids } })

/**
 * 检查配置键是否已存在
 * @param key 配置键
 * @param id 当前配置ID（可选，编辑时使用）
 */
export const checkConfigKeyExists = (key: string, id?: string) =>
  request.get<API.Response<boolean>>('/api/config/check-key', { params: { key, id } })

/**
 * 获取指定分组下的配置数量
 * @param groupId 分组ID
 */
export const getConfigCountByGroup = (groupId: string) =>
  request.get<API.Response<number>>(`/api/config/group/${groupId}/count`) 